/*
 * All dialogs, 2008-5-16
 */

var dialogs = {};

/**
 * configure relationship.
 */
function configRelation(rel) {
    var gridIndex = -1;
    var relation = rel;
    var tables = [];
    for (var i = 0; i < globalVar.mappingTables.length; i++) {
        tables.push(globalVar.mappingTables[i].table);
    }
    var subTable = relation.subject.parent.table;
    var objTable = relation.object.parent.table;
    var width = Math.round(screen.width / 2);
    var height = Math.round(screen.height / 2);
    var win = new OAT.Window({close:1, min:0, max:0, width:width, height:height, title:"Configure Mapping & Conditions", magnetsH:2}, OAT.WindowData.TYPE_AUTO);
    var configArea = OAT.Dom.create("div",{},"config_area");
    var buttons = OAT.Dom.create("div",{},"wizard_buttons");
    var subjectArea = OAT.Dom.create("div",{},"subject_area");
    var objectArea = OAT.Dom.create("div",{},"object_area");	
    var reflistArea = OAT.Dom.create("div",{},"ref_list");
    var condArea = OAT.Dom.create("div",{},"condition_area");
    // subject and object dropdown list selector
    var subTableList = new OAT.Combolist([], "Subject", {name:"subject", imagePath:"images/"});
    var objTableList = new OAT.Combolist([], "Object", {name:"object", imagePath:"images/"});
    var subColumnList = new OAT.Combolist([], "Column", {name:"subCol", imagePath:"images/"});
    var objColumnList = new OAT.Combolist([], "Column", {name:"objCol", imagePath:"images/"});
    for (var i = 0; i < tables.length; i++) {
	    subTableList.addOption(tables[i].uri);
	    objTableList.addOption(tables[i].uri);
    }
    subTableList.onchange = function () {
	    subColumnList.clearOpts();
	    for (var i = 0; i < tables.length; i++) {
	        var tb = tables[i].uri;
	        if (tb == subTableList.value) {
                var columns = tables[i].columns;
		        for (var j = 0; j < columns.length; j++) {
		            subColumnList.addOption(columns[j].uri);
		        }
	        }
	    }
    };
    objTableList.onchange = function () {
	    objColumnList.clearOpts();
	    for (var i = 0; i < tables.length; i++) {
	        var tb = tables[i].uri;
	        if (tb == objTableList.value) {
                var columns = tables[i].columns;
		        for (var j = 0; j < columns.length; j++) {
		            objColumnList.addOption(columns[j].uri);
		        }
	        }
	    }
    };
    subjectArea.appendChild(new OAT.Dom.text("Subject"));
    subjectArea.appendChild(subTableList.div);
    objectArea.appendChild(new OAT.Dom.text("Object: "));
    objectArea.appendChild(objTableList.div);
    subjectArea.appendChild(new OAT.Dom.text("Subject column: "));
    subjectArea.appendChild(subColumnList.div);
    objectArea.appendChild(new OAT.Dom.text("Object column: "));
    objectArea.appendChild(objColumnList.div);
    var subAddBtn = new OAT.Dom.button("Add");
    var objAddBtn = new OAT.Dom.button("Add");
    OAT.Dom.attach(subAddBtn, "click", function () {
	    if (subColumnList.value != "Column") {
            var subId = 0;
            for (var i = 0; i < tables.length; i++) {
                if (subTableList.value == tables[i].uri) {
                    subId = tables[i].id;
                    break;
                }
            }
            var index = grid.rows.length;
	        grid.createRow([{value:"ref" + (index + 1),align:OAT.GridData.ALIGN_CENTER}, {value:subColumnList.value,align:OAT.GridData.ALIGN_CENTER}, {value:subId,align:OAT.GridData.ALIGN_CENTER}]);
	    } else {
	        alert("Choose column please!");
	    }
    });
    OAT.Dom.attach(objAddBtn, "click", function () {
	    if (objColumnList.value != "Column") {
            var objId = 0;
            for (var i = 0; i < tables.length; i++) {
                if (objTableList.value == tables[i].uri) {
                    objId = tables[i].id;
                    break;
                }
            }
            var index = grid.rows.length;
	        grid.createRow([{value:"ref" + (index + 1),align:OAT.GridData.ALIGN_CENTER}, {value:objColumnList.value,align:OAT.GridData.ALIGN_CENTER}, {value:objId,align:OAT.GridData.ALIGN_CENTER}]);
	    } else {
	        alert("Choose column please!");
	    }
    });
    subjectArea.appendChild(subAddBtn);
    objectArea.appendChild(objAddBtn);
    /* Internet Explorer does not display correctly.
    var grid = new OAT.Grid(reflistArea, {allowColumnHiding:false});
    */
    var grid = new OAT.Grid(reflistArea, {imagePath:"images/"});
    grid.createHeader([{value:"id", align:OAT.GridData.ALIGN_CENTER}, {value:"ref string", align:OAT.GridData.ALIGN_CENTER}, {value:"father", align:OAT.GridData.ALIGN_CENTER}]);
    // condition
    var rmBtnArea = OAT.Dom.create("div");
    rmBtnArea.style.right = 10;
    var rmBtn = new OAT.Dom.button("Remove");
    OAT.Dom.attach(rmBtn, "click", function() {
        for (var i = 0; i < grid.rows.length; i++) {
            if (grid.rows[i].selected) {
                grid.rows[i].clear();
            }
        }
    });
    var con = OAT.Dom.create("span");
    rmBtnArea.appendChild(rmBtn);
    condArea.appendChild(rmBtnArea);
    condArea.appendChild(new OAT.Dom.text("Conditions:"));
    con.appendChild(new OAT.Dom.text("###ref1### = ###ref2###"));
    condArea.appendChild(con);
    OAT.QuickEdit.assign(con, OAT.QuickEdit.STRING, []);
    var btnNext = new OAT.Dom.button("Next");
    OAT.Dom.attach(btnNext, "click", function () {
        relation.join = new JoinInfo();
        relation.join.left = "Subject";
        relation.join.right = objTableList.value;
        relation.join.condition = con.innerHTML;
        for (var i = 0; i < grid.rows.length; i++) {
            var row = grid.rows[i];
            if (!row.cells.length)
                continue;
            var ref = new Ref(row.cells[0].value.innerHTML, row.cells[1].value.innerHTML,  row.cells[2].value.innerHTML);
            relation.join.addRef(ref);
        }
        for (var i = 0; i < tables.length; i++) {
            if (subTableList.value == tables[i].uri)
                relation.join.subId = tables[i].id;
            if (objTableList.value == tables[i].uri)
                relation.join.objId = tables[i].id;
        }
        grid.clearData();
        subColumnList.clearOpts();
        objColumnList.clearOpts();
        btnNext.disabled = true;
    });
    
    var btnFinish = new OAT.Dom.button("Finish");
    OAT.Dom.attach(btnFinish, "click", function () {
        relation.color = "blue";
        if (relation.join) {
            var tmpJoin = relation.join;
            relation.join = new JoinInfo();
	        relation.join.left = "Join";
	        relation.join.leftJoin = tmpJoin;
        } else {
            relation.join = new JoinInfo();
            relation.join.left = "Subject";
        }
        relation.join.right = "Object";
        relation.join.condition = con.innerHTML;
        for (var i = 0; i < grid.rows.length; i++) {
            var row = grid.rows[i];
            if (!row.cells.length)
                continue;
            var ref = new Ref(row.cells[0].value.innerHTML, row.cells[1].value.innerHTML,  row.cells[2].value.innerHTML);
            relation.join.addRef(ref);
        }
        for (var i = 0; i < tables.length; i++) {
            if (subTableList.value == tables[i].uri)
                relation.join.subId = tables[i].id;
            if (objTableList.value == tables[i].uri)
                relation.join.objId = tables[i].id;
        }
	    OAT.Dom.hide(win.div);
	    OAT.Dom.unlink(win.div);
        delete win;
        delete grid;
        delete subTableList;
        delete objTableList;
        delete subColumnList;
        delete objColumnList;
        OAT.Dom.show(globalVar.canvas);
        relation.draw();
    });
    var btnCancel = new OAT.Dom.button("Cancel");
    OAT.Dom.attach(btnCancel, "click", function () {
        relation.color = "red";
	    OAT.Dom.hide(win.div);
	    OAT.Dom.unlink(win.div);
        delete win;
        delete grid;
        delete subTableList;
        delete objTableList;
        delete subColumnList;
        delete objColumnList;
        OAT.Dom.show(globalVar.canvas);
        relation.draw();
    });
    win.onclose = function() {
        OAT.Dom.hide(win.div);
        OAT.Dom.unlink(win.div);
        delete win;
        delete grid;
        delete subTableList;
        delete objTableList;
        delete subColumnList;
        delete objColumnList;
        OAT.Dom.show(globalVar.canvas);
        relation.draw();
    }
    configArea.appendChild(subjectArea);
    configArea.appendChild(objectArea);
    configArea.appendChild(reflistArea);
    configArea.appendChild(condArea);
    win.content.appendChild(configArea);
    buttons.appendChild(btnNext);
    buttons.appendChild(btnFinish);
    buttons.appendChild(btnCancel);
    win.content.appendChild(buttons);
    document.body.appendChild(win.div);
    OAT.Dom.hide(globalVar.canvas);
    OAT.Dom.show(win.div);
    OAT.Dom.center(win.div, 1, 1);
}

// add more options
/** XMLA connection setup and WebDav initialization. */
function initProject() {
    if (dialogs.connection) {
        dialogs.connection.show();
        return;
    }
    $("xmla_endpoint").value = "/XMLA";
    $("user").value = httpCred.username;
    $("passowrd").value = httpCred.password;
    $("quad_storage_name").value = saveOption.storage;
    $("ms_graph_name").value = saveOption.graph;
    $("ms_graph_uri").value = saveOption.uri;
    dialogs.connection = new OAT.Dialog("New Project", "new_project", {width:500,modal:1,buttons:1});
    $("new_project").style.display = "";
    OAT.Dom.attach("xmla_endpoint", "blur", function() {
        xmlaDSN();
    });
    OAT.Dom.attach("xmla_dsn", "click", function() {
        if ($("xmla_dsn").childNodes.length == 0) {
            xmlaDSN();
        }
    });
    OAT.Dom.attach("user", "change", function() {
        httpCred.username = $v("user");
    });
    OAT.Dom.attach("password", "change", function() {
        httpCred.password = $v("password");
    });
    OAT.Dom.attach("login_put_type", "change", function() {
        if ($("xmla_dsn").childNodes.length == 0) {
            xmlaDSN();
        }
    });
    dialogs.connection.cancel = dialogs.connection.hide;
    dialogs.connection.okBtn.setAttribute("disabled", "disabled");
    dialogs.connection.show();
    dialogs.connection.ok = function() {
        OAT.Dom.show(globalVar.canvas);
        globalVar.projectId = 1;
        globalVar.projectType = $v("project_type");
        saveOption.storage = $v("quad_storage_name");
        saveOption.graph = $v("ms_graph_name");
        saveOption.uri = $v("ms_graph_uri");
        if (globalVar.projectType == "publish_rdf") {
            publishRdf();
        } else {
            xmlaDbSchema();
        }
        var opts = {
            user:httpCred.username,
            pass:httpCred.password,
            path:saveOption.defaultDavPath,
            isDav:true
        };
        OAT.WebDav.init(opts);
    };
}

/**
 * Configure IRI when mapping a table to a ontology
 */
function configIRI(mo) {
    if (mo.type != "MappingOnto") {
        return;
    }
    var self = this;
    this.primaryKey = [];
    this.mo = mo;
    this.table = mo.parent.table;
    this.iriClass = true;
    var tbs = $("create_iri_class").getElementsByTagName("table");
    for (var i = tbs.length; i > 0; i--) {
        OAT.Dom.unlink(tbs[i]);
    }
    dialogs.configIRI = new OAT.Dialog("Config IRI", "create_iri_class", {width:550,modal:1,button:1});
    // initilize dialog content
    var select = $("iri_class_prefix");
    OAT.Dom.clear(select);
    for (var prop in prefixMap) {
        var prefix = prefixMap[prop];
        if (prefix.shortcut) {
            OAT.Dom.option(prefix.shortcut, prefix.shortcut, select);
        }
    }
    $("iri_class_name").value = self.table.name + "_iri";
    $("iri_column_args").value = "not null";
    var columns = self.table.columns;
    select = $("iri_table_column");
    OAT.Dom.clear(select);
    for (var i = 0; i < columns.length; i++) {
        OAT.Dom.option(columns[i].name, columns[i].name, select);
    }
    select = $("iri_column_datatype");
    OAT.Dom.clear(select);
    for (var i = 0; i < sqlData.length; i++) {
        OAT.Dom.option(sqlData[i], sqlData[i], select);
    }
    $("iri_column_value").innerHTML = "";
    $("iri_convert_rule").value = "http://^{URIQADefaultHost}^/" + saveOption.graph + "/" + self.table.name + "?id=%d#this";
    $("create_iri_class").style.display = "";
    OAT.Dom.attach("iri_class_prefix", "click", function() {
        var select = $("iri_class_prefix");
        if (select.childNodes.length == 0) {
            dialogs.configIRI.hide();
            prefixManage(self.mo);
        }
    });
    OAT.Dom.attach("iri_select", "click", function() {
        var radios = document.getElementsByName("iri_radio");
        for (var i = 0; i < radios.length; i++) {
            if (radios[i].checked) {
                if (radios[i].value == "iri_const") {
                    $("const_iri_row").style.display = "";
                    $("iri_class_row").style.display = "none";
                    iriClass = false;
                    break;
                } else if (radios[i].value == "iri_class") {
                    $("const_iri_row").style.display = "none";
                    $("iri_class_row").style.display = "";
                    iriClass = true;
                    break;
                }
            }
        }
    });
    this.addNewColumn = function() {
        var columnValue = $v("iri_table_column");
        for (var i = 0; i < self.primaryKey.length; i++) {
            if (self.primaryKey[i][0] == columnValue) {
                // already added
                return;
            }
        }
        var key = [ $v("iri_table_column"),$v("iri_column_datatype"),$v("iri_column_args") ];
        self.primaryKey.push(key);
        var value = $("iri_column_value").innerHTML;
        if (value !== "")
            value += ", ";
        value += $v("iri_table_column") + " " + $v("iri_column_datatype") + " " + $v("iri_column_args");
        $("iri_column_value").innerHTML = value;
    };
    OAT.Dom.attach("iri_add_column", "click", self.addNewColumn);
    dialogs.configIRI.cancel = dialogs.configIRI.hide;
    dialogs.configIRI.ok = function() {
        if (iriClass) {
            var prefix = $("iri_class_prefix").value;
            if (!prefix || prefix == "") {
                alert("please select a prefix.");
                return;
            }
            var name = $v("iri_class_name");
            if (!name || name == "") {
                alert("please specify the name of IRI class.");
                return;
            }
            var convertRule = $v("iri_convert_rule");
            if (!convertRule || convertRule == "") {
                alert("please specify sprintf style format string for conversion.");
                return;
            }
            if (self.primaryKey.length == 0) {
                alert("please specify primay key of table.");
                return;
            }
            var data = {
                constIRI:false,
                name:prefix + ":" + name,
                conv:convertRule,
                primaryKey:self.primaryKey,
                str:""
            };
            self.mo.iriClass = data;
            self.mo.hasIRIClass = true;
        } else {
            var constStr = $v("const_iri_value");
            if (constStr == "") {
                alert("please specify iri value");
                return;
            }
            var data = {
                constIRI:true,
                name:"",
                conv:"",
                primaryKey:null,
                str:constStr
            }
            self.mo.iriClass = data;
            self.mo.hasIRIClass = true;
        }
        dialogs.configIRI.hide();
        OAT.Dom.detach("iri_add_column", "click", self.addNewColumn);
        delete dialogs.configIRI;
    }
    dialogs.configIRI.show();
}

/**
 * dialog to manage prefixs.
 */
function prefixManage(mo) {
    if (dialogs.prefix) {
        dialogs.prefix.show();
        return;
    }
    $("prefix_shortcut").value = "";
    $("prefix_prefix").value = "";
    var grid = new OAT.Grid("prefix_list",{allowColumnHiding:false});
    grid.fromTable("prefix_table");
    for (var prop in prefixMap) {
        var prefix = prefixMap[prop];
        if (prefix.shortcut && prefix.prefix) {
            /*
            var tbl = $("prefix_table");
            var newRow = tbl.insertRow(-1);
            var cell = newRow.insertCell(0);
            cell.innerHTML = prefix.shortcut;
            cell = newRow.insertCell(1);
            cell.innerHTML = prefix.prefix;
            */
            var rowData = [
                {
                    value:prefix.shortcut,
                    resizable:true,
                    align:OAT.Grid.SORT_CENTER,
                    type:OAT.Grid.TYPE_STRING
                },
                 {
                     value:prefix.prefix,
                     resizable:true,
                     align:OAT.Grid.SORT_CENTER,
                     type:OAT.Grid.TYPE_STRING
                 }
            ]
            grid.createRow(rowData);
        }
    }
    dialogs.prefix = new OAT.Dialog("Manage prefix", "prefix_manage", {width:500,modal:1,buttons:1});
    $("prefix_manage").style.display = "";
    OAT.Dom.attach("add_new_prefix", "click", function() {
        var name = $v("prefix_shortcut");
        var prefix = $v("prefix_prefix");
        if (name == "undefined" || name == "") {
            alert("please specify shortcut for prefix.");
            return;
        }
        if (prefix == "undefined" || prefix == "") {
            alert("please specify prefix value.");
            return;
        }
        if (!prefixMap[prefix]) {
            var data = {
                shortcut:name,
                prefix:prefix
            };
            prefixMap[prefix] = data;
            /*
            var tbl = $("prefix_table");
            var newRow = tbl.insertRow(-1);
            var cell = newRow.insertCell(0);
            cell.innerHTML = name;
            cell = newRow.insertCell(1);
            cell.innerHTML = prefix;
            */
            var rowData = [
                {
                    value:name,
                    resizable:true,
                    align:OAT.Grid.SORT_CENTER,
                    type:OAT.Grid.TYPE_STRING
                },
                 {
                     value:prefix,
                     resizable:true,
                     align:OAT.Grid.SORT_CENTER,
                     type:OAT.Grid.TYPE_STRING
                 }
            ]
            grid.createRow(rowData);
        }
    });
    dialogs.prefix.ok = function() {
        dialogs.prefix.hide();
        if (mo) {
            configIRI(mo);
        }
    }
    dialogs.prefix.cancel = function() {
        dialogs.prefix.hide();
        if (mo) {
            configIRI(mo);
        }
    }
    dialogs.prefix.show();
}

/**
 * About and credits dialogs.
 */
function about() {
    if (dialogs.about) {
        dialogs.about.show();
        return;
    }
    dialogs.about = new OAT.Dialog("About", "about", {width:500,modal:1,buttons:1});
    $("about").style.display = "";
    dialogs.about.ok = dialogs.about.hide;
    dialogs.about.cancel = dialogs.about.hide;
    dialogs.about.show();
}

function configUrlRewrite() {
    if (dialogs.urlRewrite) {
        dialogs.urlRewrite.show();
        return;
    }
    dialogs.urlRewrite = new OAT.Dialog("URL Rewriting", "config_url_rewrite", {width:600,modal:1,buttons:1});
    var grid = new OAT.Grid("url_rewrite_rules_list", { allowColumnHiding:false });
    grid.fromTable("all_url_rewrite_rules_table");
    for (var i = 0; i < urlRewriteRules.length; i++) {
        var rule = urlRewriteRules[i];
        var row = [
            {
                value:rule.ruleIRI,
                resizable:true,
                align:OAT.Grid.SORT_CENTER,
                type:OAT.Grid.TYPE_STRING
            },
            {
                value:rule.niceMatch,
                resizable:true,
                align:OAT.Grid.SORT_CENTER,
                type:OAT.Grid.TYPE_STRING
            },
            {
                value:rule.acceptPattern,
                resizable:true,
                align:OAT.Grid.SORT_CENTER,
                type:OAT.Grid.TYPE_STRING
            },
            {
                value:rule.httpRedirectCodes,
                resizable:true,
                align:OAT.Grid.SORT_CENTER,
                type:OAT.Grid.TYPE_STRING
            }
        ]
        grid.createRow(row);
    }
    $("config_url_rewrite").style.display = "";
    dialogs.urlRewrite.cancel = dialogs.urlRewrite.hide;
    dialogs.urlRewrite.ok = function() {
        dialogs.urlRewrite.hide();
    }
    dialogs.urlRewrite.show();
    OAT.Dom.attach("url_rewrite_save", "click", function() {
        var index = -1;
        var ruleIRI = $v("url_rewrite_rule_iri");
        var allowUpdate = $("url_rewrite_allow_update").checked ? 1 : 0;
        var dontContinue = $("url_rewrite_do_not_continue").checked ? 1 : 0;
        var httpRedirectCode = $v("url_rewrite_red_code");
        var niceMatch = $v("url_rewrite_nice_match");
        var acPattern = $v("url_rewrite_ac_pattern");
        var niceParam = $v("url_rewrite_nice_params");
        var niceMinParam = $v("url_rewrite_nice_min");
        var targetParam = $v("url_rewrite_target_params");
        var targetCompose = $v("url_rewrite_target_compose");
        if (ruleIRI == "") {
            alert("IRI is empty");
            return;
        }
        for (var i = 0; i < urlRewriteRules.length; i++) {
            if (ruleIRI == urlRewriteRules[i].ruleIRI) {
                index = i;
                break;
            }
        }
        if (index > -1) {
            // modify exsit url rewriting rule
            var rule = urlRewriteRules[index];
            if (allowUpdate == 1 || allowUpdate == 0) {
                if (allowUpdate != rule.allowUpdate) {
                    rule.allowUpdate = allowUpdate;
                }
            }
            if (dontContinue == 1 || dontContinue == 0) {
                if (dontContinue != rule.doNotContinue) {
                    rule.doNotContinue == dontContinue;
                }
            }
            if (httpRedirectCode && httpRedirectCode != rule.httpRedirectCodes) {
                rule.httpRedirectCodes = httpRedirectCode;
            }
            if (niceMatch && niceMatch != rule.niceMatch) {
                rule.niceMatch = niceMatch;
            }
            if (niceMinParam && niceMinParam != rule.niceMinParams) {
                rule.niceMinParams = niceMinParam;
            }
            if (targetParam && targetParam != rule.taretParams) {
                rule.targetParams = targetParam;
            }
            if (targetCompose && targetCompose != rule.targetCompose) {
                rule.targetCompose = targetCompose;
            }
            urlRewriteRules[index] == rule;
        } else {
            // add new url rewriting rule
            if (allowUpdate != 1 && allowUpdate != 0) {
                alert("Allow update?");
                return;
            }
            if (dontContinue != 1 && dontContinue != 0) {
                alert("Do not conitnue?");
                return;
            }
            if (!httpRedirectCode) {
                alert("http redirect code?");
                return;
            }
            if (!niceMatch) {
                alert("nice match pattern?");
                return;
            }
            if (!niceMinParam) {
                alert("nice min parameters?");
                return;
            }
            if (!targetParam) {
                alert("target parameters?");
                return;
            }
            if (!targetCompose) {
                alert("target compose?");
                return;
            }
            var data = {
                ruleIRI:"\'" + ruleIRI + "\'",
                allowUpdate:"\'" + allowUpdate + "\'",
                niceMatch:"\'" + niceMatch + "\'",
                niceParams:"\'" + niceParam + "\'",
                niceMinParams:"\'" + niceMinParam + "\'", 
                targetCompose:"\'" + targetCompose + "\'",
                targetParams:"\'" + targetParam + "\'",
                targetExpn:"null",
                acceptPattern:"\'" + acPattern + "\'",
                doNotContinue:"\'" + dontContinue + "\'",
                httpRedirectCodes:"\'" + httpRedirectCode + "\'"
            }
            urlRewriteRules.push(data);
            var rowData = [
                {
                    value:ruleIRI,
                    resizable:true,
                    align:OAT.Grid.SORT_CENTER,
                    type:OAT.Grid.TYPE_STRING
                },
                {
                    value:niceMatch,
                    resizable:true,
                    align:OAT.Grid.SORT_CENTER,
                    type:OAT.Grid.TYPE_STRING
                },
                {
                    value:acPattern,
                    resizable:true,
                    align:OAT.Grid.SORT_CENTER,
                    type:OAT.Grid.TYPE_STRING
                },
                {
                    value:httpRedirectCode,
                    resizable:true,
                    align:OAT.Grid.SORT_CENTER,
                    type:OAT.Grid.TYPE_STRING
                }
            ]
            grid.createRow(row)
        }
    });
}
